#include <algorithm>

#include "Query.h"

Query::Query(OperatorNode *n)
	: node(n), parent(0)
{
}

/*Query::Query(const Query &query)
{
	node = query.node;
	parent = query.parent;

	for (std::vector <Query *> :: const_iterator i = query.lists.begin(); i != query.lists.end(); ++i)
	{
		lists.push_back(new Query(**i));
	}
}*/

Query::~Query()
{
	node = 0;
	for (std::vector <Query *> :: iterator i = lists.begin(); i != lists.end(); i++)
	{
		delete *i;
	}

	delete node;
}

void Query::addOperator(OperatorNode *node)
{
	lists.push_back(new Query(node));
	(*(lists.end() - 1))->parent = this;
}

void Query::clear()
{
	delete this;
}

QueryInfo::QueryInfo(Query *q, int n)
	: query(q), number(n), cost(-1)
{
}

QueryInfo::~QueryInfo()
{
	query->clear();
}

QueryStorage::QueryStorage()
{
}

QueryStorage::~QueryStorage()
{
	for (std::vector <QueryInfo *> :: iterator i = queries.begin(); i != queries.end(); i++)
	{
		delete *i;
	}
}

void QueryStorage::addQuery(QueryInfo *qi)
{
	queries.push_back(qi);
}

void QueryStorage::deleteQuery(QueryInfo *qi)
{
	std::vector <QueryInfo *> :: iterator i = std::find(queries.begin(), queries.end(), qi);

	while (i != queries.end())
	{
		QueryInfo *qi = *i;

		queries.erase(i);

		delete qi;

		i = std::find(queries.begin(), queries.end(), qi);
	}
}

void QueryStorage::deleteQuery(int number)
{
	for (std::vector <QueryInfo *> :: iterator i = queries.begin(); i != queries.end(); i++)
	{
		if ((*i)->number == number)
		{
			delete *i;
		}
	}
}

bool QueryStorage::empty()
{
	return queries.empty();
}

Query *QueryStorage::getQuery(int number)
{
	for (std::vector <QueryInfo *> :: iterator i = queries.begin(); i != queries.end(); i++)
	{
		if ((*i)->number == number)
		{
			return (*i)->query;
		}
	}

	return 0;
}

void Query::getOpsList(std::vector <OperatorNode *> &opsList)
{
	opsList.push_back(node);

	for (std::vector <Query *> :: iterator i = lists.begin(); i != lists.end(); ++i)
	{
		(*i)->getOpsList(opsList);
	}
}

void Query::setOpsList(std::vector <OperatorNode *> :: iterator it)
{
	node = *it;

	for (std::vector <Query *> :: iterator i = lists.begin(); i != lists.end(); ++i)
	{
		(*i)->setOpsList(++it);
	}
}

int QueryStorage::size()
{
	return queries.size();
}